<template>
  <div class="execution-view">
    <div class="header">
      <h2>执行历史</h2>
      <div class="filters">
        <el-select v-model="filters.status" placeholder="状态" clearable>
          <el-option label="全部" value="" />
          <el-option label="等待中" value="pending" />
          <el-option label="执行中" value="running" />
          <el-option label="已完成" value="completed" />
          <el-option label="失败" value="failed" />
        </el-select>
        <el-date-picker
          v-model="filters.dateRange"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          value-format="YYYY-MM-DD"
        />
      </div>
    </div>

    <el-card>
      <el-table
        :data="executions"
        style="width: 100%"
        v-loading="loading"
      >
        <el-table-column prop="id" label="ID" width="180" />
        <el-table-column prop="workflow.title" label="工作流" min-width="180">
          <template #default="{ row }">
            <div class="workflow-info">
              <el-image
                :src="row.workflow?.cover"
                :preview-src-list="[row.workflow?.cover]"
                fit="cover"
                class="workflow-cover"
              />
              <span>{{ row.workflow?.title }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getStatusType(row.status)">
              {{ getStatusText(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="startTime" label="开始时间" width="180">
          <template #default="{ row }">
            {{ formatDate(row.startTime) }}
          </template>
        </el-table-column>
        <el-table-column prop="endTime" label="结束时间" width="180">
          <template #default="{ row }">
            {{ row.endTime ? formatDate(row.endTime) : '-' }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button-group>
              <el-button
                size="small"
                :disabled="!canViewResult(row)"
                @click="viewResult(row)"
              >
                查看结果
              </el-button>
              <el-button
                size="small"
                type="primary"
                :disabled="!canRetry(row)"
                @click="retryExecution(row)"
              >
                重试
              </el-button>
            </el-button-group>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination">
        <el-pagination
          v-model:current-page="page"
          v-model:page-size="pageSize"
          :total="total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next"
          @size-change="handleSizeChange"
          @current-change="handlePageChange"
        />
      </div>
    </el-card>

    <!-- 结果查看对话框 -->
    <el-dialog
      v-model="resultDialog.visible"
      title="执行结果"
      width="800px"
    >
      <div class="result-content">
        <template v-if="resultDialog.status === 'completed'">
          <div v-if="resultDialog.images?.length" class="result-images">
            <el-image
              v-for="(image, index) in resultDialog.images"
              :key="index"
              :src="image"
              :preview-src-list="resultDialog.images"
              fit="cover"
            />
          </div>
          <div v-else class="no-result">
            <el-empty description="暂无结果" />
          </div>
        </template>
        <template v-else-if="resultDialog.status === 'failed'">
          <div class="error-message">
            {{ resultDialog.error || '执行失败' }}
          </div>
        </template>
      </div>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { format } from 'date-fns'
import { executor } from '@/services/executor'
import type { ExecutionRecord } from '@/types/workflow'

// 过滤条件
const filters = ref({
  status: '',
  dateRange: [] as string[]
})

// 分页
const page = ref(1)
const pageSize = ref(10)
const total = ref(0)
const loading = ref(false)

// 执行记录
const executions = ref<ExecutionRecord[]>([])

// 结果对话框
const resultDialog = ref({
  visible: false,
  status: '' as 'completed' | 'failed',
  images: [] as string[],
  error: ''
})

// 获取执行记录
const getExecutions = async () => {
  try {
    loading.value = true
    const params = {
      page: page.value,
      limit: pageSize.value,
      status: filters.value.status,
      startDate: filters.value.dateRange[0],
      endDate: filters.value.dateRange[1]
    }
    const response = await executor.getExecutionHistory(params)
    executions.value = response.items
    total.value = response.total
  } catch (error) {
    console.error('Failed to get executions:', error)
    ElMessage.error('获取执行记录失败')
  } finally {
    loading.value = false
  }
}

// 查看结果
const viewResult = async (execution: ExecutionRecord) => {
  try {
    const result = JSON.parse(execution.result || '{}')
    resultDialog.value = {
      visible: true,
      status: execution.status as 'completed' | 'failed',
      images: result.images || [],
      error: execution.error || ''
    }
  } catch (error) {
    console.error('Failed to parse result:', error)
    ElMessage.error('解析结果失败')
  }
}

// 重试执行
const retryExecution = async (execution: ExecutionRecord) => {
  try {
    await executor.retryExecution(execution.id)
    ElMessage.success('重试已开始')
    getExecutions()
  } catch (error) {
    console.error('Failed to retry execution:', error)
    ElMessage.error('重试失败')
  }
}

// 获取状态类型
const getStatusType = (status: string) => {
  switch (status) {
    case 'completed':
      return 'success'
    case 'failed':
      return 'danger'
    case 'running':
      return 'warning'
    default:
      return 'info'
  }
}

// 获取状态文本
const getStatusText = (status: string) => {
  switch (status) {
    case 'completed':
      return '已完成'
    case 'failed':
      return '失败'
    case 'running':
      return '执行中'
    case 'pending':
      return '等待中'
    default:
      return status
  }
}

// 检查是否可以查看结果
const canViewResult = (execution: ExecutionRecord) => {
  return execution.status === 'completed' || execution.status === 'failed'
}

// 检查是否可以重试
const canRetry = (execution: ExecutionRecord) => {
  return execution.status === 'failed'
}

// 格式化日期
const formatDate = (date: string) => {
  return format(new Date(date), 'yyyy-MM-dd HH:mm:ss')
}

// 处理分页
const handleSizeChange = (size: number) => {
  pageSize.value = size
  getExecutions()
}

const handlePageChange = (currentPage: number) => {
  page.value = currentPage
  getExecutions()
}

// 初始化
onMounted(() => {
  getExecutions()
})
</script>

<style scoped lang="scss">
.execution-view {
  padding: 24px;

  .header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 24px;

    h2 {
      margin: 0;
    }

    .filters {
      display: flex;
      gap: 16px;
    }
  }

  .workflow-info {
    display: flex;
    align-items: center;
    gap: 12px;

    .workflow-cover {
      width: 40px;
      height: 40px;
      border-radius: 4px;
    }
  }

  .pagination {
    margin-top: 24px;
    text-align: right;
  }

  .result-content {
    .result-images {
      display: grid;
      grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
      gap: 16px;

      .el-image {
        width: 100%;
        height: 200px;
        border-radius: 4px;
        overflow: hidden;
      }
    }

    .error-message {
      color: var(--el-color-danger);
      text-align: center;
      padding: 24px;
    }

    .no-result {
      padding: 24px;
    }
  }
}
</style> 